package com.hongji.lms5xxcommunicator.realtime.websoket;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

@Slf4j
@Component
@RequiredArgsConstructor
public class StreamHandler extends org.springframework.web.socket.handler.TextWebSocketHandler {

    private final StreamHub hub;

    /** 握手成功：登记会话，并“连接即回放”缓存的 gridSpec + full 帧 */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("[WS] handshake OK -> {}", session.getId());
        hub.add(session); // ★ 这里会触发补发（你改过的 StreamHub.add() 里已实现）
    }

    /** 连接关闭：移除会话 */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        hub.remove(session);
        log.info("[WS] closed {} - {}", session.getId(), status);
    }

    /** 收到前端消息（可选）：收到 'ready' 再补发一次（双保险） */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        log.debug("[WS] recv {}: {}", session.getId(), payload);
        if (payload != null) {
            String p = payload.trim();
            if ("ready".equalsIgnoreCase(p) || "{\"type\":\"ready\"}".equalsIgnoreCase(p)) {
                if (hub.getLastGridSpecJson() != null && session.isOpen()) {
                    session.sendMessage(new TextMessage(hub.getLastGridSpecJson()));
                }
                if (hub.getLastFullFrameJson() != null && session.isOpen()) {
                    session.sendMessage(new TextMessage(hub.getLastFullFrameJson()));
                }
            }
        }
    }

    /** 传输异常（可选） */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.warn("[WS] transport error {} - {}", session != null ? session.getId() : "N/A", exception.getMessage(), exception);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
